package com.xk857.simpleeffect.activity;

import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.Settings;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.xk857.simpleeffect.R;
import com.xk857.simpleeffect.db.PersonDataBase;
import com.xk857.simpleeffect.domain.Result;
import com.xk857.simpleeffect.domain.entity.Customer;
import com.xk857.simpleeffect.domain.param.UpdateMeParam;
import com.xk857.simpleeffect.enums.RequestEnum;
import com.xk857.simpleeffect.utils.OkHttpUtils;
import com.xuexiang.xui.widget.actionbar.TitleBar;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;
import com.xuexiang.xui.widget.toast.XToast;

import java.io.File;
import java.lang.reflect.Type;
import java.util.function.Consumer;

import cn.hutool.core.util.StrUtil;
import de.hdodenhof.circleimageview.CircleImageView;

public class UpdatePersonMeActivity extends AppCompatActivity {

    private TitleBar titleBar;
    private CircleImageView imageView;
    private TextView imageTextView;
    private EditText nickNameEdit;
    private TextView phoneText;
    private Button updateButton;


    private static final int PICK_IMAGE_REQUEST = 1;
    private static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 2;

    private static RequestOptions requestOptions = new RequestOptions()
            .placeholder(R.mipmap.loading)
            .error(R.drawable.icon_error_24)
            .transform(new CircleCrop());
    private File file = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        getWindow().setStatusBarColor(ContextCompat.getColor(this, R.color.white));
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        setContentView(R.layout.activity_update_person_me_actvity);
        initView();
        initData();
    }

    private void initData() {
        Customer dbCustomer = PersonDataBase.getPersonInfo(this);
        if (dbCustomer != null) {
            Glide.with(this).load(dbCustomer.getHeadImg()).apply(requestOptions).into(imageView);
            phoneText.setText(dbCustomer.getUsername());
            nickNameEdit.setText(dbCustomer.getNickName());
        }
        // 更新按钮，点击发送请求，更新个人信息
        updateButton.setOnClickListener(v -> updatePersonMe());
        imageView.setOnClickListener(v -> showFileChooser());
        imageTextView.setOnClickListener(v -> showFileChooser());
    }

    /**
     * 用户修改头像点击事件，调用系统相册，动态权限申请
     */
    private void showFileChooser() {
        // 如果当前用户没给权限，则弹出权限申请
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
        } else {
            Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            intent.setType("image/**");
            startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
        }
    }


    private void initView() {
        titleBar = findViewById(R.id.title_bar);
        titleBar.setLeftClickListener(v -> finish());
        imageView = findViewById(R.id.imageView);
        imageTextView = findViewById(R.id.image_text_view);
        nickNameEdit = findViewById(R.id.nick_name_edit);
        phoneText = findViewById(R.id.phone_text);
        updateButton = findViewById(R.id.update_button);
    }

    /**
     * 获取动态权限申请结果，成功：打开相册；失败：弹出提示框跳转到修改权限界面
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 执行打开相册的操作
                Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, PICK_IMAGE_REQUEST);
            } else {
                new MaterialDialog.Builder(this).iconRes(R.drawable.icon_error_24).title(R.string.error).content("您拒绝了系统获取文件的权限，请前往设置打开‘读写手机存储’权限").positiveText(R.string.yes).onPositive((dialog, which) -> {
                    Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                    intent.setData(Uri.fromParts("package", getPackageName(), null));
                    startActivity(intent);
                }).show();
            }
        }
    }

    /**
     * 用户选择完图片回调此函数
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
            // 获取图片 Uri
            Uri imageUri = data.getData();
            // 使用 OkHttp 上传图片
            file = new File(getRealPathFromURI(imageUri));
            Glide.with(this).load(file).into(imageView);
//            uploadImage(file);
        }
    }


    private void uploadImage(File file, Consumer<String> consumer) {
        Type type = new TypeToken<Result<String>>() {
        }.getType();
        OkHttpUtils.getInstance().uploadFile(this, RequestEnum.UPLOAD_IMAGE, type, file, (Consumer<String>) url ->
                runOnUiThread(() -> {
                    Glide.with(this).load(url).apply(requestOptions).into(imageView);
                    // 上传修改个人信息
                    consumer.accept(url);
                }));
    }

    /**
     * 更新个人信息
     */
    private void updatePersonMe() {
        if (StrUtil.isBlankIfStr(nickNameEdit.getText().toString()) || nickNameEdit.getText().toString().length() < 2) {
            XToast.info(this, "昵称不能小于两位").show();
            return;
        }
        if (nickNameEdit.getText().toString().length() >= 12) {
            XToast.info(this, "昵称要在12位以内").show();
            return;
        }

        UpdateMeParam param = new UpdateMeParam();
        param.setNickName(nickNameEdit.getText().toString());

        if (file != null) {
            uploadImage(file, url -> {
                // 上传图片，将url传递给param
                param.setHeadImg(url);
                sendUpdate(param);
            });
        }else {
            sendUpdate(param);
        }

    }

    private void sendUpdate(UpdateMeParam param) {
        Type type = new TypeToken<Result<Customer>>() {}.getType();
        OkHttpUtils.getInstance().put(this, RequestEnum.UPDATE_PERSON_ME, type, param, true, (Consumer<Customer>) customer -> {
            Gson gson = new Gson();
            SharedPreferences preferences = this.getSharedPreferences("userInfo", MODE_PRIVATE);
            SharedPreferences.Editor edit = preferences.edit();
            edit.putString("token", customer.getToken());
            edit.putString("customer", gson.toJson(customer));
            edit.apply();//提交

            runOnUiThread(() -> new MaterialDialog.Builder(this)
                    .iconRes(R.drawable.icon_info)
                    .title(R.string.info)
                    .content("修改成功")
                    .positiveText(R.string.yes)
                    .show());
        });
    }

    private String getRealPathFromURI(Uri uri) {
        String[] projection = {MediaStore.Images.Media.DATA};
        Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
        if (cursor == null) {
            return null;
        }
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        String filePath = cursor.getString(column_index);
        cursor.close();
        return filePath;
    }
}